/*
 *  Copyright (c) 2023-2025 苏州棱镜七彩信息科技有限公司 (Suzhou PrismAurora Information Technology Co.,Ltd)
 *  sbom-generate is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *           http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 * */
package com.ljqc.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @ClassName CommandUtils
 * @Description
 * @Date 2022/8/8 17:03
 * @Version V1.0
 **/
public final class CommandUtils {
    private CommandUtils() {

    }

    private static final Logger LOGGER = Logger.getLogger(CommandUtils.class.getName());

    private static final String COMMAND_PREFIX_1;
    private static final String COMMAND_PREFIX_2;
    public static boolean isWindows;

    static {
        isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
        COMMAND_PREFIX_1 = isWindows ? "cmd" : "/bin/sh";
        COMMAND_PREFIX_2 = isWindows ? "/c" : "-c";
    }

    /**
     * 执行命令
     *
     * @param command
     * @date 2025/3/13 16:32
     */
    public static String run(String command, boolean returnResult) {
        StringBuilder result = new StringBuilder();
        ProcessBuilder pb = new ProcessBuilder(COMMAND_PREFIX_1, COMMAND_PREFIX_2, command).redirectErrorStream(true);
        Process process = null;
        try {
            process = pb.start();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")))) {
                String content;
                while ((content = br.readLine()) != null) {
                    if (returnResult) {
                        result.append(content).append("\n");
                    }
                    LOGGER.log(Level.FINE, content);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return result.toString();
    }

    public static void run(String command) {
        run(command, false);
    }
}
